import React from 'react'

const scaleName = {
  c: 'Celsius',
  f: 'Fahrenheit'
}
// 摄氏度和华摄度转换
function toCelsius (fahrenheit) {
  return ((fahrenheit - 32) * 5) / 9
}

function toFahrenheit (celsius) {
  return (celsius * 9) / 5 + 32
}
// 对传进来的数值进行处理
function tryConvert (temperature, convert) {
  const input = parseFloat(temperature) // 向上取整
  if (Number.isNaN(input)) {
    return ''
  }
  const outPut = convert(input)
  const rouded = Math.round(outPut * 1000) / 1000 // 四舍五入
  return rouded.toString() // 转成字符串
}
// 温度是否烧开
function BoilingVerdict (props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>
  }
  return <p>The water would not boil.</p>
}

class TemperatureInput extends React.Component {
  constructor (props) {
    super(props)
    console.log(props, 'props');
  }
  handleChange = e => {
    console.log(this.props.onTemperatureChange)
    this.props.onTemperatureChange(e.target.value)
  }
  render () {
    const { temperature, scale } = this.props
    return (
      <fieldset>
        <length>Enter temperature in {scaleName[scale]}</length>
        <input value={temperature} onChange={this.handleChange}></input>
      </fieldset>
    )
  }
}
class Calculator3 extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      temperature: '',
      scale: 'c'
    }
  }
  handleCelsiusChange=(temperature)=>{
      this.setState({
          scale: 'c',
          temperature
      })
  }
  handleFahrenheitChange=(temperature)=>{
    this.setState({
        scale: 'f',
        temperature
    })
  }
  render(){
      const { scale, temperature } = this.state
      const celsius = scale === 'f' ? tryConvert(temperature, toCelsius):temperature
      const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature
      return (<div>
          <TemperatureInput scale='c' temperature={celsius} onTemperatureChange={this.handleCelsiusChange}></TemperatureInput>
          <TemperatureInput scale='f' temperature={fahrenheit} onTemperatureChange={this.handleFahrenheitChange}></TemperatureInput>
          <BoilingVerdict celsius={parseFloat(celsius)}></BoilingVerdict>
      </div>)
  }
}
export {Calculator3}